<?php


namespace app\control\controller\admin;


use app\common\model\admin\Admin;
use app\common\model\member\Member;
use app\common\model\member\Recharge;
use app\common\model\member\Withdrawal;
use app\common\model\product\Order;
use app\common\model\product\Product;
use app\Request;
use think\Db;

class Statistic
{
    public function staff(Request $request)
    {
        $input = $request->post();
        $pageIndex = empty($input['pageIndex']) ? 1 : $input['pageIndex'];
        $pageSize = empty($input['pageSize']) ? 10 : $input['pageSize'];
        $total = 0;
        $filters = [];
        if (!empty($input['username'])) {
            $filters['username'] = $input['username'];
        }
        $filters['type'] = 'staff';
        $dataSet = Admin::search($filters, $pageIndex, $pageSize, $total);
        unset($filters['username']);
        $time = strtotime(date('Y-m-d'));
        if (!empty($input['timeStart'])) {
            $filters['timeCreatedStart'] = strtotime($input['timeStart']);
        } else {
            $filters['timeCreatedStart'] = $time;
        }
        if (!empty($input['timeEnd'])) {
            $filters['timeCreatedEnd'] = strtotime($input['timeEnd']);
        } else {
            $filters['timeCreatedEnd'] = $time + 86399;
        }
        $filters['ghost'] = 0;
        $returnSet = array_map(function ($row) use ($filters) {
            $filters['staffId'] = $row['id'];
            //注册人数
            $memberList = Member::search([], 0);
            $memberListCount = Member::search($filters, 0);
            $row['memberCount'] = count($memberListCount);
            $row['memberCountList'] = $memberListCount;
            $memberListNew = [];
            foreach ($memberList as $k => $v) {
                $memberListNew[$v['id']] = $v;
            }
            ////充值
            $row['recharge1'] = 0; //首充
            $row['recharge1money'] = 0; //首充
            $row['recharge1List'] = [];
            $row['recharge2'] = 0; //2充
            $row['recharge2money'] = 0; //2充
            $row['recharge2List'] = [];
            $row['recharge3'] = 0; //3充
            $row['recharge3money'] = 0; //3充
            $row['recharge3List'] = [];
            $row['recharge4'] = 0; //复充
            $row['recharge4money'] = 0; //复充
            $row['recharge4List'] = [];
            $row['rechargeCount'] = 0;//总充值
            $row['rechargeCountList'] = [];
            $filters['status']= 'success';
                unset($filters['type']);
            $rechargeList = Recharge::search($filters, 0);
            foreach ($rechargeList as $recharge) {
                $recharge['username'] = $memberListNew[$recharge['memberId']]['username'];
                $recharge['memo'] = $memberListNew[$recharge['memberId']]['memo'];
                if ($recharge['number'] == 1) {
                    $row['recharge1']++;
                    $row['recharge1money'] += $recharge['money'];
                    $row['recharge1List'][] = $recharge;
                } elseif ($recharge['number'] == 2) {
                    $row['recharge2']++;
                    $row['recharge2money'] += $recharge['money'];
                    $row['recharge2List'][] = $recharge;
                } elseif ($recharge['number'] == 3) {
                    $row['recharge3']++;
                    $row['recharge3money'] += $recharge['money'];
                    $row['recharge3List'][] = $recharge;
                } else {
                    $row['recharge4']++;
                    $row['recharge4money'] += $recharge['money'];
                    $row['recharge4List'][] = $recharge;
                }
                $row['rechargeCount'] += $recharge['money'];
            }
            $row['rechargeCountList'] = $rechargeList;
            ///////////订单
            $row['orderPeople'] = 0;//投注人数
            $tmpPeople = [];
            $filters['noPadding'] = 1;
            $orderList = Order::search($filters, 0);
            $row['orderCount'] = count($orderList);
            $row['orderMoney'] = 0;//投注金额
            $row['orderMoneyWin'] = 0;//中奖金额
            foreach ($orderList as &$order) {
                $order['username'] = $memberListNew[$order['memberId']]['username'];
                $order['memo'] = $memberListNew[$order['memberId']]['memo'];
                if (empty($tmpPeople[$order['memberId']])) {
                    $tmpPeople[$order['memberId']] = $memberListNew[$order['memberId']];
                    $tmpPeople[$order['memberId']]['orderMoney'] = $order['moneyOrder'];
                    $tmpPeople[$order['memberId']]['orderMoneyWin'] = $order['moneyOrderWin'];
                    $tmpPeople[$order['memberId']]['orderNumber'] = 1;
                    $row['orderPeople'] += 1;
                } else {
                    $tmpPeople[$order['memberId']]['orderMoney'] += $order['moneyOrder'];
                    $tmpPeople[$order['memberId']]['orderMoneyWin'] += $order['moneyOrderWin'];
                    $tmpPeople[$order['memberId']]['orderNumber'] += 1;
                }
                $row['orderMoney'] += $order['moneyOrder'];
                $row['orderMoneyWin'] += $order['moneyOrderWin'];
                $order['code'] = $order['field'] . $order['value'];
                unset($order);
            }
            $row['orderCountList'] = $orderList;
            $row['orderPeopleList'] = array_merge($tmpPeople);
            $row['orderProfit'] = round($row['orderMoney'] - $row['orderMoneyWin'], 2);//盈利

            /////提现
            $row['withdrawalMember'] = 0;
            $row['withdrawalSystem'] = 0;
            $filters['status'] = 'success';
            $withdrawalList = Withdrawal::search($filters, 0);
            foreach ($withdrawalList as $withdrawal) {
                if ($withdrawal['status'] == 'success') {
                    if ($withdrawal['type'] == 'member') {
                        $row['withdrawalMember'] += $withdrawal['money'];
                    } else {
                        $row['withdrawalSystem'] += $withdrawal['money'];
                    }
                }
            }
            return $row;
        }, $dataSet);
        return payload(['dataSet' => $returnSet, 'total' => $total]);
    }

    public function team(Request $request)
    {
        $input = $request->post();
        $pageIndex = empty($input['pageIndex']) ? 1 : $input['pageIndex'];
        $pageSize = empty($input['pageSize']) ? 10 : $input['pageSize'];
        $total = 0;
        $filters = [];
        if (!empty($input['username'])) {
            $filters['username'] = $input['username'];
        }
        $filters['type'] = 'team';
        $dataSet = Admin::search($filters, $pageIndex, $pageSize, $total);
        unset($filters['username']);
        $time = strtotime(date('Y-m-d'));
        if (!empty($input['timeStart'])) {
            $filters['timeCreatedStart'] = strtotime($input['timeStart']);
        } else {
            $filters['timeCreatedStart'] = $time;
        }
        if (!empty($input['timeEnd'])) {
            $filters['timeCreatedEnd'] = strtotime($input['timeEnd']);
        } else {
            $filters['timeCreatedEnd'] = $time + 86399;
        }
        $filters['ghost'] = 0;
        $returnSet = array_map(function ($row) use ($filters) {
            $filters['teamId'] = $row['id'];
            //注册人数
            $memberList = Member::search([], 0);
            $memberListCount = Member::search($filters, 0);
            $row['memberCount'] = count($memberListCount);
            $row['memberCountList'] = $memberListCount;
            $memberListNew = [];
            foreach ($memberList as $k => $v) {
                $memberListNew[$v['id']] = $v;
            }
            ////充值
            $row['recharge1'] = 0; //首充
            $row['recharge1money'] = 0; //首充
            $row['recharge1List'] = [];
            $row['recharge2'] = 0; //2充
            $row['recharge2money'] = 0; //2充
            $row['recharge2List'] = [];
            $row['recharge3'] = 0; //3充
            $row['recharge3money'] = 0; //3充
            $row['recharge3List'] = [];
            $row['recharge4'] = 0; //复充
            $row['recharge4money'] = 0; //复充
            $row['recharge4List'] = [];
            $row['rechargeCount'] = 0;//总充值
            $row['rechargeCountList'] = [];
            $filters['status'] = 'success';
            unset($filters['type']);
            //   var_dump($filters);return;
            $rechargeList = Recharge::search($filters, 0);
            foreach ($rechargeList as $recharge) {
                $recharge['username'] = $memberListNew[$recharge['memberId']]['username'];
                $recharge['memo'] = $memberListNew[$recharge['memberId']]['memo'];
                if ($recharge['number'] == 1) {
                    $row['recharge1']++;
                    $row['recharge1money'] += $recharge['money'];

                    $row['recharge1List'][] = $recharge;
                } elseif ($recharge['number'] == 2) {
                    $row['recharge2']++;
                    $row['recharge2money'] += $recharge['money'];

                    $row['recharge2List'][] = $recharge;
                } elseif ($recharge['number'] == 3) {
                    $row['recharge3']++;
                    $row['recharge3money'] += $recharge['money'];

                    $row['recharge3List'][] = $recharge;
                    $row['recharge4']++;
                    $row['recharge4money'] += $recharge['money'];


                    $row['recharge4List'][] = $recharge;
                }
                $row['rechargeCount'] += $recharge['money'];
            }
            $row['rechargeCountList'] = $rechargeList;
            ///////////订单
            $row['orderPeople'] = 0;//投注人数
            $tmpPeople = [];
            $filters['noPadding'] = 1;
            $orderList = Order::search($filters, 0);
            $row['orderCount'] = count($orderList);
            $row['orderMoney'] = 0;//投注金额
            $row['orderMoneyWin'] = 0;//中奖金额
            foreach ($orderList as &$order) {
                $order['username'] = $memberListNew[$order['memberId']]['username'];
                $order['memo'] = $memberListNew[$order['memberId']]['memo'];
                if (empty($tmpPeople[$order['memberId']])) {
                    $tmpPeople[$order['memberId']] = $memberListNew[$order['memberId']];
                    $tmpPeople[$order['memberId']]['orderMoney'] = $order['moneyOrder'];
                    $tmpPeople[$order['memberId']]['orderMoneyWin'] = $order['moneyOrderWin'];
                    $tmpPeople[$order['memberId']]['orderNumber'] = 1;
                    $row['orderPeople'] += 1;
                } else {
                    $tmpPeople[$order['memberId']]['orderMoney'] += $order['moneyOrder'];
                    $tmpPeople[$order['memberId']]['orderMoneyWin'] += $order['moneyOrderWin'];
                    $tmpPeople[$order['memberId']]['orderNumber'] += 1;
                }
                $row['orderMoney'] += $order['moneyOrder'];
                $row['orderMoneyWin'] += $order['moneyOrderWin'];
                $order['code'] = $order['field'] . $order['value'];
                unset($order);
            }
            $row['orderCountList'] = $orderList;
            $row['orderPeopleList'] = array_merge($tmpPeople);
            $row['orderProfit'] = round($row['orderMoney'] - $row['orderMoneyWin'], 2);//盈利

            /////提现
            $row['withdrawalMember'] = 0;
            $row['withdrawalSystem'] = 0;
            $filters['status'] = 'success';
            $withdrawalList = Withdrawal::search($filters, 0);
            foreach ($withdrawalList as $withdrawal) {
                if ($withdrawal['status'] == 'success') {
                    if ($withdrawal['type'] == 'member') {
                        $row['withdrawalMember'] += $withdrawal['money'];
                    } else {
                        $row['withdrawalSystem'] += $withdrawal['money'];
                    }
                }
            }
            return $row;
        }, $dataSet);
        return payload(['dataSet' => $returnSet, 'total' => $total]);
    }

    public function index(Request $request)
    {
        $input = $request->post();
        $where2 = [];
        if (!empty($input['timeCreatedEnd'])) {
            $where2[] = ['time_created','<=',strtotime($input['timeCreatedEnd']) + 86399];
        }
        if (!empty($input['timeCreatedStart'])) {
            $where2[] = ['time_created','>=',strtotime($input['timeCreatedStart'])];
        }
        $startTime = strtotime(date('Y-m-d'));
        $endTime = strtotime(date('Y-m-d')) + 86399;
        $data = [
            'orderMoneyCount' => 0, //总流水
            'orderMoneyDayCount' => 0,
            'orderMoneyWinCount' => 0,//总盈亏
            'orderMoneyWinDayCount' => 0,
            'orderCount' => 0,//订单数量
            'orderDayCount' => 0,
            'orderMemberCount' => 0,//下单用户数量
            'orderMemberDayCount' => 0,

            'memberCount' => 0,//会员数量
            'memberDayCount' => 0,
            'memberRechargeCount' => 0,//充值金额
            'memberRechargeDayCount' => 0,
            'memberWithdrawalCount' => 0,//提现金额
            'memberWithdrawalDayCount' => 0,
            'memberValidCount' => 0,//有效用户
        ];
        $where = [
            'ghost' => 0
        ];
        //总流水
        $data['orderMoneyCount'] = Db::table('product_orders')->where($where2)->where($where)->sum('money_order');
        $data['orderMoneyDayCount'] = Db::table('product_orders')->where($where)->whereBetween('time_created',"$startTime,$endTime")->sum('money_order');
        //盈亏
        $data['orderMoneyWinCount'] = $data['orderMoneyCount'] - Db::table('product_orders')->where($where2)->where(['ghost' => 0,'is_win' => 'win'])->sum('order_win');
        $data['orderMoneyWinDayCount'] = $data['orderMoneyDayCount'] - Db::table('product_orders')->where(['ghost' => 0,'is_win' => 'win'])->whereBetween('time_created',[$startTime,$endTime])->sum('order_win');
        //订单数量
        $data['orderCount'] =  Db::table('product_orders')->where($where2)->where($where)->count();
        $data['orderDayCount'] = Db::table('product_orders')->where($where)->whereBetween('time_created',"$startTime,$endTime")->count();
        //下单用户数量
        $data['orderMemberCount'] = Db::table('product_orders')->where($where)->where($where2)->group('member_id')->count();
        $data['orderMemberDayCount'] = Db::table('product_orders')->where($where)->whereBetween('time_created',"$startTime,$endTime")->group('member_id')->count();

        //会员数量
        $data['memberCount'] = Db::table('members')->where($where)->count();
        $data['memberValidCount'] = Db::table('members')->where($where)->where($where2)->where('money','>',0)->count();
        $data['memberDayCount'] = Db::table('members')->where($where)->whereBetween('time_created',"$startTime,$endTime")->count();
        //充值金额
        $data['memberRechargeCount'] = Db::table('member_recharges')->where($where)->where($where2)->where(['status' => 'success'])->where('source','<>','caijin')->sum('money');
        $data['memberRechargeDayCount'] = Db::table('member_recharges')->where($where)->where(['status' => 'success'])->where('source','<>','caijin')->whereBetween('time_created',"$startTime,$endTime")->sum('money');
        //提现金额
        $data['memberWithdrawalCount'] = Db::table('member_withdrawals')->where($where)->where($where2)->where(['status' => 'success'])->sum('money');
        $data['memberWithdrawalDayCount'] = Db::table('member_withdrawals')->where($where)->where(['status' => 'success'])->whereBetween('time_created',"$startTime,$endTime")->sum('money');
        //
        return payload(['data' => $data]);
    }

    public function product(Request $request)
    {
        $input = $request->post();
        $productDataSet = Product::search([]);
        $returnSet = [];
        $filters = [];
        $filters[] = ['ghost','=',0];
        if (!empty($input['timeCreatedStart'])) {
            $filters[] = ['time_created', '>=', strtotime($input['timeCreatedStart'])];
        }
        if (!empty($input['timeCreatedEnd'])) {
            $filters[] = ['time_created', '<=', strtotime($input['timeCreatedEnd']) + 86399];
        }
//        var_dump($where);
        foreach ($productDataSet as $v) {
            $data = [];
            $where = $filters;
            $data['title'] = $v['lang'][0]['name'];
            $where[] = ['name','=',$v['name']];
            $data['orderMoneyCount'] = Db::table('product_orders')->where($where)->sum('money_order');//总流水
            $data['orderMoneyWinCount'] = $data['orderMoneyCount'] - Db::table('product_orders')->where($where)->where(['is_win' => 'win'])->sum('order_win');//总盈亏
            $data['orderCount'] =  Db::table('product_orders')->where($where)->count();//订单数量
            $data['orderMemberCount'] = Db::table('product_orders')->where($where)->group('member_id')->count();//下单人数
            $data['orderPointCount'] = Db::table('product_orders')->where($where)->where(['is_win' => 'win'])->sum('point');//总获手续费
            $returnSet[] = $data;
        }
        return payload(['dataSet' => $returnSet]);
    }

    public function statistic(Request $request)
    {
        $input = $request->post();
        $time = strtotime(date('Y-m-d'));
        if (!empty($input['timeStart'])) {
            $filters['timeCreatedStart'] = strtotime($input['timeStart']);
        } else {
            $filters['timeCreatedStart'] = $time;
        }
        if (!empty($input['timeEnd'])) {
            $filters['timeCreatedEnd'] = strtotime($input['timeEnd']);
        } else {
            $filters['timeCreatedEnd'] = $time + 86399;
        }
        $filters['ghost'] = 0;
        $data = [
            'memberCount' => 0, //注册数
//            'memerCountList' => [],
            'memberMoneyCount' => 0, //用户总余额
            'recharge1' => 0, //首充人数
            'rechargeMoney' => 0, //总充值
            'withdrawalMoney' => 0, //总提现
            'withdrawalMemberMoney' => 0,
            'withdrawalSystemMoney' => 0,
            'monthProfitNow' => 0,
            'monthProfitLast' => 0,
        ];
        $memberList = Member::search($filters, 0);
        $data['memberCount'] = count($memberList);
        foreach ($memberList as $member) {
            $data['memberMoneyCount'] += $member['money'];

        }
        $filters['status'] = 'success';
        $rechargeList = Recharge::search($filters, 0);
        foreach ($rechargeList as $recharge) {
            if ($recharge['number'] == 1) {
                $data['recharge1'] += 1;
            }
            $data['rechargeMoney'] += $recharge['money'];
        }
        $withdrawalList = Withdrawal::search($filters, 0);
        foreach ($withdrawalList as $withdrawal) {
            if ($withdrawal['type'] == 'system') {
                $data['withdrawalSystemMoney'] += $withdrawal['money'];
            } else {
                $data['withdrawalMemberMoney'] += $withdrawal['money'];
            }
            $data['withdrawalMoney'] += $withdrawal['money'];
        }
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $orderFilters = [
            'timeCreatedStart' => $beginThismonth,
            'timeCreatedEnd' => $endThismonth,
            'ghost' => 0
        ];
        $orderList = Order::search($orderFilters, 0);
        foreach ($orderList as $order) {
            $data['monthProfitNow'] += round(($order['moneyOrder'] - $order['moneyOrderWin']), 2);
        }
        $time = $this->getMontylast();
        $orderFilters = [
            'timeCreatedStart' => $time['start'],
            'timeCreatedEnd' => $time['end'],
            'ghost' => 0
        ];
        $orderList = Order::search($orderFilters, 0);
        foreach ($orderList as $order) {
            $data['monthProfitLast'] += round(($order['moneyOrder'] - $order['moneyOrderWin']), 2);
        }
        $data['monthProfitNow'] = round($data['monthProfitNow'], 2);
        $data['monthProfitLast'] = round($data['monthProfitLast'], 2);
        $data['rechargeMoney'] = round($data['rechargeMoney'], 2);
        $data['withdrawalMoney'] = round($data['withdrawalMoney'], 2);
        return payload(['dataSet' => [$data], 'total' => 1]);
    }


    public function getMontylast()
    {
        $thismonth = date('m');
        $thisyear = date('Y');
        if ($thismonth == 1) {
            $lastmonth = 12;
            $lastyear = $thisyear - 1;
        } else {
            $lastmonth = $thismonth - 1;
            $lastyear = $thisyear;
        }
        $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
        $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));
        $b_time = strtotime($lastStartDay);//上个月的月初时间戳
        $e_time = strtotime($lastEndDay);//上个月的月末时间戳
        return [
            'start' => $b_time,
            'end' => $e_time + 86399,
        ];
    }
}